// 上厅堂首页
const app = getApp();
var server = require('../../utils/server');
var common = require('../../utils/common');
var amapFile = require('../../libs/amap-wx');
Page({
  data: {
    isLogin: true,
    showPhonePop: false,
    showLoginPop: false,
    isDisableLog: false,
    isDisableReg: false,
    isLocate: true,
    timestamp: (Date.parse(new Date())),
    logoMtop: 20,
    showBtnPop: true,
    aniStyle: true,
    showBanner: false,
    showBannerPop: false,
    curFrName: '',
    curBannerImg: '',
    curSecName: '',
    curBannerDesc:'',
    showNoRightPop: false,
    packetUrl: "",
    packetScene: "",
    showPage: '',
    hbLists: [],
    showRedPackets: false,
    pic_url: "",
    title1: "",
    coupon_params: "",
    isCanGetCoupon:true,
    goodProducts: [{
      "name": '尖端食材',
      "desc": '资深全球买手为你挑选尖端食材',
      "secname": '私享总监买手选货',
      'pic_url': 'http://static.sungivenfood.com/xcx/stt/icon1.png'
    }, {
      "name": '新品尝鲜',
      "desc": '每月皆有新品，轻松吃遍头鲜',
      "secname": '当季好货抢先尝',
      'pic_url': 'http://static.sungivenfood.com/xcx/stt/icon2.png'
    }, {
      "name": '内购资格',
      "desc": '详询您的专属客服可获得更多信息',
      "secname": '员工内购同款同价',
      'pic_url': 'http://static.sungivenfood.com/xcx/stt/icon3.png'
    }],
    benefitsList: [{
      "name": '下单送调味食材',
      "desc": ' 根据主厨推荐菜单，赠送葱姜蒜等调味食材',
      "secname": '无需买菜 每单1次',
      'pic_url': 'http://static.sungivenfood.com/xcx/stt/icon4.png'
    }, {
      "name": '下单送菜',
      "desc": '肉禽海鲜生鲜产品，下单即送绿叶菜一份',
      "secname": '根据订单免费搭配',
      'pic_url': 'http://static.sungivenfood.com/xcx/stt/icon5.png'
    }, {
      "name": '运费券',
      "desc": '不定期发放',
      "secname": '不定期发放',
      'pic_url': 'http://static.sungivenfood.com/xcx/stt/icon6.png'
    }],
    payServices: [{
      "name": '专车专送',
      "desc": '按你指定时间进行专线配送',
      "secname": '包车专为你送',
      'pic_url': 'http://static.sungivenfood.com/xcx/stt/icon7.png',
      "price": '80元/次'
    }, {
      "name": '生鲜分切',
      "desc": '肉禽海鲜生鲜产品，可安排需求进行分切（是否能满足分切以服务大使确认为准）',
      "secname": '按需加工',
      'pic_url': 'http://static.sungivenfood.com/xcx/stt/icon8.png',
      "price": '20元/次'
    }, {
      "name": '定期配',
      "secname": '米面粮油定期到家',
      "desc": '服务权益开发中',
      'pic_url': 'http://static.sungivenfood.com/xcx/stt/icon9.png',
      "price": ''
    }],
    coupon_value:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getLocation();
    if (app.globalData.sdkversion > 210 && app.globalData.sdkversion != 1997 && app.globalData.sdkversion != 1991) {
      console.log(wx.getMenuButtonBoundingClientRect())
      this.setData({
        logoMtop: wx.getMenuButtonBoundingClientRect().top == 0 ? 20 : wx.getMenuButtonBoundingClientRect().top,
      })
    }
  },
  getLocation() {
    wx.stopPullDownRefresh();
    if (app.globalData.longitude != null && app.globalData.latitude != null && app.globalData.city != "") {
      this.getUserInfo();
    } else {
      var gdMap = new amapFile.AMapWX({
        key: common.gdKey
      });
      gdMap.getRegeo({
        success: res => {
          app.globalData.location = res[0].regeocodeData.pois[0] == undefined ? res[0].name : res[0].regeocodeData.pois[0].name;
          app.globalData.longitude = res[0].longitude;
          app.globalData.latitude = res[0].latitude;
          app.globalData.city = res[0].regeocodeData.addressComponent.city;
          app.globalData.locateLongitude = res[0].longitude;
          app.globalData.locateLatitude = res[0].latitude;
          app.globalData.locateCity = res[0].regeocodeData.addressComponent.city;
          app.globalData.locateProvince = res[0].regeocodeData.addressComponent.province;
          this.getUserInfo();
          this.setData({
            isLocate: true
          })
          app.globalData.isLocate = true;
        },
        fail: info => {
          this.setData({
            isLocate: false
          })
          app.globalData.isLocate = false;
          wx.hideLoading();
        }
      })
    }

  },
  getUserInfo() {
    wx.getStorage({
      key: 'userInfo',
      success: res => {
        this.setData({
          isLogin: true,
          showPhonePop: false,
          showLoginPop: false
        })
        this.checkUserVip();
      },
      fail: res => {
        this.checkRegister();
      }
    })
  },
  checkUserVip() {
    server.postJSON(common.basePath + 'vip/level/', '', res => {
      if (res.data.errno == '0') {
        var data=res.data.data;
        this.setData({
          showNoRightPop: data.level == 0 ? true : false,
          noGetRedPag: data.level != 0&&data.get_time==0 ? true : false,
          coupon_value:data.coupon_value
        })
        if (data.level!=0) {
          if(data.get_time!=0){
            wx.redirectTo({
              url: 'productListsBySTT',
            })
          }else{
            this.setData({
              showPage: data
            })
          }
        } 
      } else {
        if(res.data.errno == '100013'){
          this.checkRegister()
        }else{
          common.showErrorToast(res.data.errmsg)
        }
      }
    })
  },
  // 打开定位
  openLocation(e) {
    if (e.detail.errMsg == "openSetting:ok" && e.detail.authSetting['scope.userLocation']) {
      app.globalData.isLocate = true;
      this.setData({
        isLocate: true
      })
      wx.getStorage({
        key: 'userInfo',
        success: res => {
          this.setData({
            isLogin: true,
            showPhonePop: false,
            showLoginPop: false
          })
        },
        fail: res => {
          this.getUserInfo();
        }
      })
    } else {
      common.showErrorToast('需要授权地理位置后使用！');
    }
  },
  checkRegister() {
    common.checkLogin().then(res => {
      if (res.errno == "0") {
        app.globalData.isGetWxUserinfo = true;
        if (JSON.stringify(res.data.member) == "{}") {
          wx.setStorage({
            key: "sso",
            data: res.data.sso,
            success: res => {}
          })
          app.globalData.openid = res.data.openid;
          console.log('未登录')
          this.setData({
            isLogin: false,
            showPage: true,
            showPhonePop: true
          })
        } else if (JSON.stringify(res.data.member) != "{}") {
          app.globalData.openid = res.data.openid;
          wx.setStorage({
            key: "sso",
            data: res.data.sso,
            success: res => {
              //登录成功函数
              this.checkUserVip();
            }
          })
          this.setData({
            showPhonePop: false,
            showLoginPop: false,
            isLogin: true
          })
          this.storageUserinfo(res.data)
        }
      } else if ((res.errMsg).indexOf('getUserInfo:fail') > -1) {
        this.setData({
          isLogin: false,
          showPage: true,
          showLoginPop: true
        })
      } else {
        common.showErrorToast(res.errmsg)
      }
    })
  },
  showLoginPop() {
    this.setData({
      showLoginPop: true
    })
  },
  hideLoginPop() {
    this.setData({
      showLoginPop: false,
      isLogin: false
    })
  },
  hidePhonePop() {
    this.setData({
      showPhonePop: false,
      isLogin: false
    })
  },
  showAgreement() {
    wx.navigateTo({
      url: '../../pages/common/agreement',
    })
  },
  //本地存储用户信息
  storageUserinfo(data) {
    wx.setStorage({
      key: "userInfo",
      data: data
    })
  },
  showCheckTel() {
    this.setData({
      showPhonePop: false
    })
    wx.navigateTo({
      url: '../../pages/common/register',
    })
  },
  getPhoneNumber: function (e) {
    this.setData({
      isDisableReg: true
    })
    if (e.detail.errMsg != "getPhoneNumber:ok") {
      wx.showToast({
        icon: 'none',
        title: '需要授权手机号后使用元初到家！',
      })
      this.setData({
        isDisableReg: false
      })
    } else {
      var that = this;
      wx.login({
        success: res => {
          this.setData({
            showPhonePop: false
          });
          server.postJSON(common.basePath + 'miniprogram/registermember/', {
            "iv": e.detail.iv,
            "encryptedData": e.detail.encryptedData,
            "js_code": res.code
          }, res => {
            if (res.data.errno == '0') {
              that.setData({
                isLogin: true,
                isDisableReg: false
              })
              that.storageUserinfo(res.data.data)
            } else {
              this.setData({
                isDisableReg: false
              })
              common.showErrorToast(res.data.errmsg);
            }
          })
        },
        fail: res => {
          this.setData({
            isDisableReg: false
          })
        }
      })
    }
  },
  login(e) {
    this.setData({
      isDisableLog: true
    })
    if (e.detail.errMsg == "getUserInfo:ok") {
      this.setData({
        showLoginPop: false,
        isDisableLog: false
      })
      this.checkRegister();
    } else {
      this.setData({
        isDisableLog: false
      })
      wx.showToast({
        icon: 'none',
        title: '需要授权用户信息使用元初到家！'
      })
    }
  },
  onPageScroll(e) {
    if (app.globalData.sdkversion > 140 && app.globalData.sdkversion != 1997 && app.globalData.sdkversion != 1991) {
      var windowHeight = wx.getSystemInfoSync().windowHeight;
      console.log(windowHeight)
      this.setData({
        menuBtnBottom: wx.getMenuButtonBoundingClientRect().top == 0 ? 58 : wx.getMenuButtonBoundingClientRect().bottom
      })
      wx.createSelectorQuery().select('.banner-lists').boundingClientRect(res => {
        if (res.top && res.top < 60) {
          this.setData({
            showBanner: true
          })
        } else {
          this.setData({
            showBanner: false
          })
        }
      }).exec()
      if (this.data.noGetRedPag) {
        wx.createSelectorQuery().select('.redbag-cont').boundingClientRect(res => {
          if (res.top < windowHeight) {
            var that = this;
            setTimeout(function () {
              that.setData({
                aniStyle: false,
                showBtnPop: false
              })
            }, 400)
          } else {
            var that = this;
            setTimeout(function () {
              that.setData({
                aniStyle: true,
                showBtnPop: true
              })
            }, 400)
          }
        }).exec()
      }
    }
  },
  goToIndex() {
    wx.switchTab({
      url: '../../pages/index/index',
    })
  },
  showBannerPop(e) {
    var currentTarget = e.currentTarget.dataset;
    this.setData({
      curFrName: currentTarget.name,
      curBannerImg: currentTarget.img,
      curSecName: currentTarget.secname,
      curBannerDesc: currentTarget.desc,
      showBannerPop: true
    })
  },
  hideBannerPop() {
    this.setData({
      showBannerPop: false
    })
  },
  goToIndex() {
    wx.switchTab({
      url: '../../pages/index/index',
    })
  },
  openRedBag() {
    this.setData({
      isCanGetCoupon:false
    })
    wx.showLoading({
      title: '领取中'
    })
    server.postJSON(common.basePath + 'vip/gift/', '', res => {
      this.setData({
        isCanGetCoupon:true
      })
      if (res.data.errno == '0') {
        wx.hideLoading();
        common.showErrorToast("领取成功");
        this.setData({
          showRedPackets: true,
          hbLists: res.data.data.coupon_list
        })
      } else {
        common.showErrorToast(res.data.errmsg)
      }
    })
  },
  showNoRight() { //测试无权限页面
    this.setData({
      showNoRightPop: true
    })
  },
  goToSttIndex() {
    wx.redirectTo({
      url: 'productListsBySTT',
    })
  },
  onPullDownRefresh(){
    this.getLocation()
  }
})